﻿using System;
using System.Web.Mvc;
using Ninject;

namespace ERP.Manager.Controllers
{
    public class DependentInjectionControllerFactory : DefaultControllerFactory
    {
        private readonly IKernel kernel;

        public DependentInjectionControllerFactory(IKernel container)
        {
            kernel = container;
        }

        protected override Type GetControllerType(string controllerName)
        {
            Type controllerType = base.GetControllerType(controllerName);
            if (controllerType == null)
            {
                controllerType = typeof(HomeController);
        
            }
            return controllerType;
        }

        protected override IController GetControllerInstance(Type controllerType)
        {
            if (controllerType == null)
         
                throw new ArgumentNullException("controllerType");


            if (!typeof(Controller).IsAssignableFrom(controllerType))
                throw new ArgumentException(string.Format(
                                                "Type requested is not a controller: {0}",
                                                controllerType.Name),
                                            "controllerType");



            var controller = kernel.Get(controllerType) as Controller;
            controller.ActionInvoker = kernel.Get<ControllerActionInvoker>();
            return controller;
        }
    }
}
